<template>
  <div class="users_container">
    <!-- 面包屑导航区域 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>用户管理</el-breadcrumb-item>
      <el-breadcrumb-item>用户列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片区域 -->
    <el-card class="box-card">
      <!-- 搜索与添加区域 -->
      <el-row :gutter="20">
        <!-- 第一列 搜索框和搜索按钮 -->
        <el-col :span="7">
          <el-input placeholder="请输入内容" v-model="queryInfo.query" clearable @clear="getUserList()">
            <el-button slot="append" icon="el-icon-search" @click="getUserList()">搜索</el-button>
          </el-input>
        </el-col>
        <!-- 第二列 添加用户按钮 -->
        <el-col :span="5">
          <el-button type="primary" @click="addDialogVisible = true">添加用户</el-button>
        </el-col>
      </el-row>
      <!-- 用户列表区域 -->
      <el-table
        :data="userList"
        stripe
        border>
          <el-table-column
            label="#"
            type="index">
          </el-table-column>
          <el-table-column
            prop="username"
            label="用户名">
          </el-table-column>
          <el-table-column
            prop="email"
            label="邮箱">
          </el-table-column>
          <el-table-column
            prop="mobile"
            label="电话">
          </el-table-column>
          <el-table-column
            prop="role_name"
            label="角色">
          </el-table-column>
          <el-table-column
            label="状态">
              <template slot-scope="scope">
                <el-switch v-model="scope.row.mg_state" @change="userStateChange(scope.row)"></el-switch>
              </template>
          </el-table-column>
          <el-table-column
            width="180px"
            label="操作">
              <template slot-scope="scope">
                <!-- 修改 -->
                <el-button type="primary" icon="el-icon-edit" size="mini" @click="showEditDialog(scope.row.id)"></el-button>
                <!-- 删除 -->
                <el-button type="danger" icon="el-icon-delete" size="mini" @click="deleteUser(scope.row.id)"></el-button>
                <!-- 分配角色 -->
                <el-tooltip effect="dark" content="分配角色" placement="top" :enterable="false">
                   <el-button type="warning" icon="el-icon-s-tools" size="mini"></el-button>
                </el-tooltip>
              </template>
          </el-table-column>
      </el-table>
      <!-- 分页区域 -->
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="queryInfo.pagenum"
        :page-sizes="[1, 2, 3, 4]"
        :page-size="queryInfo.pagesize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total">
      </el-pagination>
      <!-- 添加用户区域 -->
      <el-dialog
        @close="addDialogClose"
        title="添加用户"
        :visible.sync="addDialogVisible"
        width="50%"
        :before-close="handleClose">
      <!-- 主体区域 -->
      <el-form
        label-width="70px"
        ref="addFormRef"
        :rules="addFormRules"
        :model="addForm">
          <!-- 用户名 -->
          <el-form-item
            label="用户名"
            prop="username">
            <el-input
              v-model="addForm.username"
              placeholder="请输入用户名">
            </el-input>
          </el-form-item>
          <!-- 密码 -->
          <el-form-item
            label="密码"
            prop="password">
            <el-input
              v-model="addForm.password"
              placeholder="请输入密码">
            </el-input>
          </el-form-item>
          <!-- 手机 -->
          <el-form-item
            label="手机号"
            prop="mobile">
            <el-input
              v-model="addForm.mobile"
              placeholder="请输入手机号">
            </el-input>
          </el-form-item>
          <!-- 邮箱 -->
          <el-form-item
            label="邮箱"
            prop="email">
            <el-input
              v-model="addForm.email"
              placeholder="请输入邮箱">
            </el-input>
          </el-form-item>
      </el-form>
      <!-- 底部区域 -->
      <span slot="footer" class="dialog-footer">
        <el-button @click="addDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addUser">确 定</el-button>
      </span>
      </el-dialog>
      <!-- 修改用户信息区域 -->
      <el-dialog
        @close="editDialogClose"
        title="修改用户信息"
        :visible.sync="editDialogVisible"
        width="50%"
        :before-close="handleClose">
      <!-- 主体 -->
      <el-form
        label-width="70px"
        :rules="editFormRules"
        ref="editFormRef"
        :model="editForm">
        <!-- 用户名 -->
        <el-form-item
          label="用户名">
          <el-input disabled v-model="editForm.username"></el-input>
        </el-form-item>
        <!-- 邮箱 -->
        <el-form-item
          prop="email"
          label="邮箱">
          <el-input v-model="editForm.email"></el-input>
        </el-form-item>
        <!-- 手机号 -->
        <el-form-item
          prop="mobile"
          label="手机号">
          <el-input v-model="editForm.mobile"></el-input>
        </el-form-item>
      </el-form>
      <!-- 底部 -->
      <span slot="footer" class="dialog-footer">
        <el-button @click="editDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="editUser">确 定</el-button>
      </span>
    </el-dialog>
    </el-card>
  </div>
</template>

<script>
export default {
  name: 'Users',
  data () {
    // 自定义验证邮箱的验证规则
    var checkEmail = (rule, value, callback) => {
      const regEmail = /^([a-zA-Z]|[0-9])(\w|\\-)+@[a-zA-Z0-9]+\.([a-zA-Z]{2,4})$/
      if (regEmail.test(value)) {
        return callback()
      }

      callback(new Error('请输入合法的邮箱'))
    }

    return {
      // 向服务器发送的数据
      queryInfo: {
        query: '',
        // 当前页数
        pagenum: 1,
        // 当前每页显示多少条数据
        pagesize: 2
      },
      // 服务器返回的用户列表
      userList: [],
      // 每页显示的数量
      total: 0,
      // 添加用户对话框显示与隐藏
      addDialogVisible: false,
      // 修i该用户信息对话框显示与隐藏
      editDialogVisible: false,
      // 保存 添加用户的信息 的对象
      addForm: {
        username: '',
        password: '',
        mobiel: '',
        email: ''
      },
      // 查询到的用户信息
      editForm: {},
      // 验证规则
      addFormRules: {
        username: [
          { required: true, message: '请输入用户名', trigger: 'blur' },
          { min: 3, max: 10, message: '长度在 3 到 10 个字符', trigger: 'blur' }
        ],
        password: [
          { required: true, message: '请输入密码', trigger: 'blur' },
          { min: 3, max: 10, message: '长度在 3 到 10 个字符', trigger: 'blur' }
        ],
        mobile: [
          { required: true, message: '请输入手机号', trigger: 'blur' },
          { min: 11, max: 11, message: '请输入正确的手机号码', trigger: 'blur' }
        ],
        email: [
          { required: true, message: '请输入邮箱', trigger: 'blur' },
          { validator: checkEmail, trigger: 'blur' }
        ]
      },
      // 修改用户 验证规则
      editFormRules: {
        email: [
          { required: true, message: '请输入邮箱', trigger: 'blur' },
          { validator: checkEmail, trigger: 'blur' }
        ],
        mobile: [
          { required: true, message: '请输入手机号', trigger: 'blur' },
          { min: 11, max: 11, message: '请输入正确的手机号码', trigger: 'blur' }
        ]
      }
    }
  },
  created () {
    // 向服务器发送请求
    this.getUserList()
  },
  methods: {
    // 向服务器发送请求的方法
    async getUserList () {
      const { data: res } = await this.$http.get('users', { params: this.queryInfo })
      if (res.meta.status !== 200) return this.$message.error('获取用户列表失败')
      this.userList = res.data.users
      this.total = res.data.total
    },
    // 监听 pagesize 变化
    handleSizeChange (newSize) {
      this.queryInfo.pagesize = newSize
      this.getUserList()
    },
    // 监听 页码值 变化
    handleCurrentChange (newPage) {
      this.queryInfo.pagenum = newPage
      this.getUserList()
    },
    // 监听 状态 变化
    async userStateChange (userInfo) {
      const { data: res } = await this.$http.put(`users/${userInfo.id}/state/${userInfo.mg_state}`)
      if (res.meta.status !== 200) {
        userInfo.mg_state = !userInfo.mg_state
        return this.$message.error('更新状态失败')
      }
      this.$message.success('更新状态成功')
    },
    // 关闭添加用户窗口
    addDialogClose () {
      this.$refs.addFormRef.resetFields()
    },
    // 右上角关闭
    handleClose () {
      this.addDialogVisible = false
      this.editDialogVisible = false
    },
    // 添加用户
    addUser () {
      this.$refs.addFormRef.validate(async valid => {
        if (valid) {
          const { data: res } = await this.$http.post('users', this.addForm)
          if (res.meta.status !== 201 && res.meta.status !== 400) {
            this.$message.error('添加用户失败')
          } else if (res.meta.status === 400) {
            this.$message.error('用户名已存在')
          } else {
            // 隐藏添加用户的对话框
            this.addDialogVisible = false
            this.$message.success('添加用户成功')
            this.getUserList()
          }
        }
      })
    },
    // 修改用户
    editUser () {
      this.$refs.editFormRef.validate(async valid => {
        if (valid) {
          const { data: res } = await this.$http.put(`users/${this.editForm.id}`, {
            email: this.editForm.email,
            mobile: this.editForm.mobile
          })
          if (res.meta.status !== 200) return this.$message.error('修改失败')
          this.$message.success('修改成功')
          this.getUserList()
        }
      })
      this.editDialogVisible = false
    },
    // 根据 id 查询 要修改的用户信息
    async showEditDialog (id) {
      this.editDialogVisible = true
      const { data: res } = await this.$http.get(`users/${id}`)
      if (res.meta.status !== 200) return this.$message.error('查询失败')
      this.editForm = res.data
    },
    // 监听 修改用户 对话框关闭事件
    editDialogClose () {
      this.$refs.editFormRef.resetFields()
    },
    //  删除用户
    async deleteUser (id) {
      const confirmResult = await this.$confirm('此操作将永久删除该用户, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).catch(err => err)
      if (confirmResult !== 'confirm') {
        return this.$message.info('已取消删除')
      }
      const { data: res } = await this.$http.delete(`users/${id}`)
      if (res.meta.status !== 200) return this.$message.error('删除失败')
      this.$message.success('删除成功')
      this.getUserList()
    }
  }
}
</script>

<style lang="less" scoped>
.el-table {
  margin-top: 15px;
  font-size: 12px;
}
.el-pagination {
  margin-top: 15px;
}
</style>
